var getServerUrl = rootPath + "s/sys/server/list";
var getmobileUrl = rootPath + "s/bike/owner/mobile";
var sendMsgUrl = rootPath + "s/sms/msg/batchsend";











/**
 * 
 * @returns
 */
function getServerList(){
	var htmlStr = "";
	$.ajax({
        url : getServerUrl,
        type : 'post',
        data :null,
        async :false,//false为同步
        success : function (res) {
            if(res.opStatus == "0"){
            	var serverArr = res.data;
            	$(serverArr).each(function(i,o){
            		htmlStr += "<div class='checkbox' > " +
			    				"<label> " +
			    				"<input type='checkbox' onChange='checkServer(this)' id='"+o.serverId+"'>" +
			    				o.serverName+
			    				"</div> ";
            	});
            }else {
            	htmlStr = "<font color='red'>获取服务器列表失败</font>"; 
            }
            
        },
        error : function (){
        	htmlStr = "<font color='red'>获取服务器列表失败</font>"; 
        }
    });
	
	htmlStr += "<div class='checkbox' > " +
				"<label> " +
				"<input type='checkbox' onChange='checkServer(this)' id='other'>" +
				"其他" +
				"</div> ";
	$("#mobileList").html(htmlStr);
	
}
/**
 * 选中
 * @param obj
 * @returns
 */
function checkServer(obj){
	var flag = $(obj).is(':checked');
	var id = $(obj).attr('id');
	var mobileStr = "";
	if(flag){//选中了
		if(id && id != "other"){
			$.ajax({
		        url : getmobileUrl,
		        type : 'post',
		        data :{"serverId":id},
		        async :false,
		        success : function (res) {
		        	var mobileArr = res.data;
		        	$(mobileArr).each(function(i,o){
		        		mobileStr += (o+",");
		        	});
		        }
		    });
		}
		
		var buttonHtml = "<button type='button' class='btn btn-link ' reason='"+id+"' onclick='mobileInput_showOrHid(this)' sta='show'><i class='glyphicon glyphicon-chevron-up' ></i>收起</button>";
		$(obj).parent().parent().append(buttonHtml);
		var textHtml = "<div class='form-group' reason='"+id+"'>" +
				"<input type='text' wrong='wrong' onclick='selectInputStr(this)' class='form-control ' name='mobiles' placeholder='多个手机号码用英文字符的逗号“,”分割开' value='"+mobileStr+"' >" +
				"</div> ";
		$(obj).parent().parent().after(textHtml);
	}else {
		var els = $("[reason="+id+"]")
		$(els).each(function(i,o){
			o.remove();
		});
	}
}
/**
 * 显示或者隐藏电话输入框
 * @returns
 */
function mobileInput_showOrHid(obj,sta){
	var id = $(obj).attr('reason');
	if(sta){
		
	}else {
		sta = $(obj).attr('sta');
	}
	if(sta == "show"){
		//开始执行隐藏的逻辑
		$(obj).attr('sta','hide');
		var iEl = "<i class='glyphicon glyphicon-chevron-down' ></i>展开";
		$(obj).html(iEl);
		$("div[reason="+id+"]").hide();
	}else {
		//开始执行显示的逻辑
		$(obj).attr('sta','show');
		var iEl = "<i class='glyphicon glyphicon-chevron-up' ></i>收起";
		$(obj).html(iEl);
		$("div[reason="+id+"]").show();
	}
}



/**
 * 根据索引值选中字符串
 * @param input
 * @param startPos
 * @param endPos
 * @returns
 */
function setSelection(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}
function getPosition (input) {
	var pos = 0;
	if (document.selection) {
		input.focus ();
		var selection = document.selection.createRange ();
		selection.moveStart ('character', -input.value.length);
		pos = selection.text.length;
	}
	else if (input.selectionStart || input.selectionStart == '0')
		pos = input.selectionStart;
	return pos;
}

/**
 * 单击了电话号码
 * @param obj
 * @returns
 */
function selectInputStr(obj){
	var input = obj;
	var val = $(obj).val();
	var click_position = getPosition(input);
	var start = val.lastIndexOf(",",click_position)+1;
	if(start == -1) start = 0;
	var end = val.indexOf(",",click_position);
	if(end == -1) end = val.length;
	setSelection(input,start,end+1);
}
/**
 * 发送短信
 * @returns
 */
function sendSmsMSG(){
	var inputArr = $("input[name=mobiles]");
	var mobileStr = "";
	//-------检验电话号码
	$(inputArr).each(function(i,o){
		var flag = mobilesMatch(o);
		var val = $(o).val();
		if(val && val != ""){
			val = $(o).val().replace("；",",");
		}
		mobileStr += val;
	});
	mobileStr = mobileStr.replace("undefined","");
	if(mobileStr == "" || mobileStr == "undefined" || inputArr.length < 1){
		showMsg('请添加手机号码！');
		return;
	}
	//判断内容是否为空
	 contentMatch();
	var len = $("[wrong]").length;
	if(len > 0){
		//有错误的手机号码
	}else {
		//验证通过
//		alert(mobileStr)
		var text = $("#send_content").val();
		var serialNumber = $("#serialNumber").val();
		$.ajax({
	        url : sendMsgUrl,
	        type : 'post',
	        data :{"mobiles":mobileStr,"text":text,"serialNumber":serialNumber},
	        async :false,
	        success : function (res) {
	        	if(res.opStatus == "0"){
	        	var button = '<button class="btn btn-default btn-xs"  type="button" onclick="goSmsRecord(\''+res.data.serialNumber+'\')"><i class="glyphicon glyphicon-hand-up"></i> 点击查看短信记录</button>';
	        	showMsg(res.msgDesc + '<br>' + "一共  "+res.data.totalCount+" 条短信，成功发送了  "+res.data.succeedCount+" 条短信" + '<br>' + '流水号是：' + res.data.serialNumber+ '<br>' + button);
	        	}else {
	        		showMsg(res.msgDesc);
	        	}
	        }
	    });
	}
	//-------检验电话号码
//	alert(mobileStr)
}
/**
 * 检查内容是否符号规则
 * @returns
 */
function contentMatch(){
	var content = $("#send_content").val();
	if(content == null || content == "" || content == "undefined"){
		$("#send_content").css("background","yellow");
		$("#send_content").attr('wrong','wrong');
		showMsg('请编辑短信内容！');
		return false;
	}else {
		$("#send_content").css("background","white");
		$("#send_content").removeAttr('wrong');
		return true;
	}
}
/**
 * 验证电话号码是否符合规则
 * @param obj
 * @returns
 */
function mobilesMatch(obj){
	var val = $(obj).val();
	if(val && val != ""){
		val = $(obj).val().replace("，",",");
		$(obj).val(val);
		if(!val.match(/^(1[3|4|5|8][0-9]\d{4,8}[,]*)+$/)){
			var id = $(obj).parent().attr('reason');
			mobileInput_showOrHid($("button[reason="+id+"]"),"hide");
			obj.style.borderColor="#ff0000";
			$(obj).attr('wrong','wrong');
			var mArr = val.split(",")
			$(mArr).each(function(i,o){
				if(!o.match(/^1[3|4|5|8][0-9]\d{4,8}$/)){
					var start = val.search(o);
					var end = val.indexOf(",",start);
					setSelection(obj,start,end);
					return false;
				}
			})
		}else {
			obj.style.borderColor="";
			$(obj).removeAttr('wrong');
			return true;
		}
	}
	
}

/**
 * 前往查看短信记录
 * @returns
 */
function goSmsRecord(serialNumber){
	var prm = { 'serialNumber' : serialNumber};
	$("#com-alert").modal('hide');
	Index.loadPage("s/sms/msg/pageList.cgi?serialNumber=" + serialNumber,null,function(){
		$("#serialNumber").val(serialNumber);
		$(".active-menu").removeClass("active-menu");
		$("a[link=\"s/sms/msg/pageList.cgi\"]").addClass("active-menu");
		 refreshGrid();
	});
}
$(document).ready(function () {
	getServerList();
	$("#send_button").on("click",function () {
		sendSmsMSG();
    });
});